﻿using System.Collections.Generic;
using System.Linq;
using Contrib.FeedsAggregator.Models;
using Contrib.FeedsAggregator.Services;
using Contrib.FeedsAggregator.ViewModels;
using Orchard.ContentManagement;
using Orchard.ContentManagement.Drivers;
using Orchard.Localization;

namespace Contrib.FeedsAggregator.Drivers {
    public class FeedPartDriver : ContentPartDriver<FeedPart> {
        private readonly IFeedsService _feedsService;

        public FeedPartDriver(IFeedsService feedsService) {
            _feedsService = feedsService;

            T = NullLocalizer.Instance;
        }

        public Localizer T { get; set; }

        protected override DriverResult Display(FeedPart feedPart, string displayType, dynamic shapeHelper) {
            FeedPartViewModel feedPartViewModel = BuildDisplayViewModel(feedPart);
            if (feedPartViewModel.FeedNews.Count() <= 0) {
                // Nothing to display
                return null;
            }

            return ContentShape(shapeHelper.Parts_FeedsAggregator_FeedPart(Feed: feedPartViewModel));
        }

        protected override DriverResult Editor(FeedPart feedPart, dynamic shapeHelper) {
            var results = new List<DriverResult> {
                ContentShape("Parts_FeedsAggregator_FeedPart",
                             () => shapeHelper.EditorTemplate(TemplateName: "Parts.FeedsAggregator.FeedPart", Model: feedPart, Prefix: Prefix))
            };

            if (feedPart.Id > 0) {
                results.Add(ContentShape("Parts_FeedsAggregator_DeleteButton",
                    deleteButton => deleteButton));
            }

            return Combined(results.ToArray());
        }

        protected override DriverResult Editor(FeedPart feedPart, IUpdateModel updater, dynamic shapeHelper) {
            updater.TryUpdateModel(feedPart, Prefix, null, null);
            return Editor(feedPart, shapeHelper);
        }

        private FeedPartViewModel BuildDisplayViewModel(FeedPart feedPart) {
            return new FeedPartViewModel {
                FeedPartRecord = feedPart.Record,
                FeedNews = _feedsService.GetNews(feedPart.Id, feedPart.SortingOrder),
            };
        }
    }
}